package com.dc.docs._888_面试.concurrent._5_ccs;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Description: 信号量
 * 临界资源允许多个线程同时访问，超过限定数量的外的线程得阻塞等待
 *
 * https://juejin.im/post/5c53a1d1e51d45705b1a1728
 *
 * @author: gdc
 * @date: 2021/6/16
 * @version 1.0
 */
public class SemaphoreDemo {

    public static void main(String[] args){
        // 模拟有三个停车位
        Semaphore semaphore = new Semaphore(3);

        // 模拟有6个车同时抢车位
        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + ", 抢到了车位");

                    int num = RandomUtil.randomInt(1, 5);
                    TimeUnit.SECONDS.sleep(num);
                    System.out.println(Thread.currentThread().getName() + "等待" + num + "秒后，离开停车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, "车_" + i).start();
        }
    }
}
